﻿#Delete IIS log files older than 1 day

param([String]$advancedLogLocation)

Function Clean-Logs{
	Param(
		[Parameter(Mandatory=$true)]
		[String]$logLocation
	)

	if ($logLocation -match "%(.*%)\\") {
		$logLocation = $logLocation -replace "%(.*%)\\","$(cmd /C echo $matches[0])"
	}

	$daysToRetain = 1
	$filetype = "*.log"
	$filestoDelete = DIR $logLocation $filetype -Recurse | where {$_.lastwritetime -lt (get-date).adddays($daysToRetain*-1)}

	if ($filesToDelete -ne $null){    
		 $filesToDelete | Foreach-Object {Add-Content c:\ClearIISLogs.log "Deleting $_"}
		 $filesToDelete| Remove-Item
	}
}

Add-Content c:\ClearIISLogs.log -value "Cleaning process started at $(Get-Date)"
Clean-Logs($advancedLogLocation)
Add-Content c:\ClearIISLogs.log -value "Cleaning process completed at $(Get-Date)"